const express = require('express');
const session = require('express-session');
const router = express.Router();
const db = require('./db');
const crypto = require('crypto');



//获取收货地址列表
router.get("/", (req, res) => {
    const authHeader = req.headers['authorization'];
    // console.log('%cbackend\addressApi.js:44 aythHeader', 'color: #007acc;', authHeader);
    const userId = req.session.userId;
    if (!userId) {
        res.status(400).json({ code: 2 });
    } else {

        const query = `select * from tpadmin_user_address WHERE user_user_id =?`;
        db.connection.query(query, [userId], (error, results) => {
            // console.log('%cbackend\addressApi.js:47 results', 'color: #007acc;', results);
            if (error) {
                console.error('登录失败:', error);
                res.status(500).json({ msg: '登录失败' });
            } else {
                if (results.length === 0) {
                    res.status(200).json({ code: 1, msg: '暂无数据' });
                } else {
                    res.status(200).json({ code: 1, msg: '', data: results })
                }
            }
        })
    }
})
//编辑保存收货地址
router.post("/save", (req, res) => {

    const { id, name, tel, area, detail } = req.body;
    const user_id = req.session.userId;
    // 在此处执行数据库操作，将数据保存到数据库中
    // 假设您使用的是 mysql 模块进行数据库操作
    // console.log('%cbackend\addressApi.js:66 user_id', 'color: #007acc;', user_id);
    if (!user_id) {
        res.status(401).json({ code: 2 });
        return;
    }

    // 根据 id 的存在与否决定执行插入还是更新操作
    if (id) {
        // 更新操作
        const updateQuery = `UPDATE tpadmin_user_address SET name = ?, tel = ?, area = ?, detail = ?, update_time = NOW() WHERE id = ? AND user_user_id = ?`;
        db.connection.query(updateQuery, [name, tel, area, detail, id, user_id], (err, result) => {
            if (err) {
                console.error('Error updating address:', err);
                res.status(500).json({
                    code: 0,
                    msg: '更新失败',
                });
            } else {
                res.status(200).json({
                    code: 1,
                    msg: '更新成功',
                });
            }
        });
    } else {
        // 插入操作
        const insertQuery = `INSERT INTO tpadmin_user_address (user_user_id, name, tel, area, detail, create_time, update_time) VALUES (?, ?, ?, ?, ?, NOW(), Now())`;
        db.connection.query(insertQuery, [user_id, name, tel, area, detail], (err, result) => {
            if (err) {
                console.error('Error saving address:', err);
                res.status(500).json({
                    code: 0,
                    msg: '保存失败',
                });
            } else {
                // 获取插入的地址记录的 ID
                const insertedId = result.insertId;
                res.status(200).json({
                    code: 1,
                    msg: '添加成功',
                    data: {
                        id: insertedId,
                    },
                });
            }
        });
    }
});
router.post("/del", (req, res) => {
    const { id } = req.body;
    const user_id = req.session.userId;
    if (!user_id) {
        res.status(401).json({ code: 2, msg: "未登录" });
        return;
    }

    // 确保请求中包含 id 参数
    if (!id) {
        res.status(400).json({ code: 0, msg: '缺少必要的参数 id' });
        return;
    }

    const query = `DELETE FROM tpadmin_user_address WHERE id = ? AND user_user_id = ?`;
    db.connection.query(query, [id, user_id], (err, result) => {
        if (err) {
            console.error('删除失败:', err);
            res.status(500).json({
                code: 0,
                msg: '删除失败',
            });
        } else {
            if (result.affectedRows > 0) {
                res.status(200).json({
                    code: 1,
                    msg: '删除成功',
                });
            } else {
                res.status(404).json({
                    code: 0,
                    msg: '未找到指定的收货地址或地址不存在',
                });
            }
        }
    });
});

// 查询需要修改的收货地址列表
router.get("/edit", (req, res) => {
    const userId = req.session.userId;
    const addressId = req.query.id;
    console.log('%cbackend\addressApi.js:137 addressId', 'color: #007acc;', addressId);
    if (!userId) {
        res.status(401).json({ code: 2, msg: "未登录" });
    } else {
        const query = `SELECT * FROM tpadmin_user_address WHERE user_user_id = ?  and id=?`;
        db.connection.query(query, [userId, addressId], (error, results) => {
            if (error) {
                console.error('查询失败:', error);
                res.status(500).json({ code: 0, msg: '查询失败' });
            } else {
                res.status(200).json({ code: 1, msg: '', data: results[0] });
            }
        });
    }
});

//默认收货地址
router.get("/def", (req, res) => {
    const userId = req.session.userId;
    const addressId = req.query.id;
    // console.log('%cbackend\addressApi.js:176 addressId', 'color: #007acc;', addressId);
    // console.log('%cbackend\addressApi.js:177 userId', 'color: #007acc;', userId);
    if (addressId === "0") {
        // 如果地址ID为0，则返回userId对应的第一个收货地址
        const query = `SELECT * FROM tpadmin_user_address WHERE user_user_id = ? ORDER BY id ASC LIMIT 1`;
        db.connection.query(query, [userId], (error, results) => {
            if (error) {
                console.error('查询失败:', error);
                res.status(500).json({ code: 0, msg: '查询失败' });
            } else {
                if (results.length > 0) {
                    res.status(200).json({ code: 1, msg: '', data: results[0] });
                } else {
                    res.status(404).json({ code: 0, msg: '未找到收货地址' });
                }
            }
        });
    } else {
        // 返回传入地址ID对应的收货地址
        const query = `SELECT * FROM tpadmin_user_address WHERE user_user_id = ? AND id = ?`;
        db.connection.query(query, [userId, addressId], (error, results) => {
            if (error) {
                console.error('查询失败:', error);
                res.status(500).json({ code: 0, msg: '查询失败' });
            } else {
                if (results.length > 0) {
                    res.status(200).json({ code: 1, msg: '', data: results[0] });
                } else {
                    res.status(404).json({ code: 0, msg: '未找到指定的收货地址' });
                }
            }
        });
    }
})
module.exports = router;
